package com.clstu.preparedstatement;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * 演示PrepareStatement的executeUpdate()方法,执行dml语句(增删改)
 */
public class PrepareStatement01 {
    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String name = scanner.nextLine();//注意这里不能用next(),next()读到空格或者'会自动结束,后面读不到了,nextLine读到换行才结束
        System.out.print("请输入密码:");//  当输入万能用户名: 1' or
        String pwd = scanner.nextLine();//      万能密码: or '1'='1 的时候,都能成功登陆 .,这就是sql注入!!!!!(甚至可能破坏你的数据)
        String sql = "insert into us values (?,?)";//增操作
//        String sql = "delete from us where name =? and pwd =?";//删操作
//        String sql = "update us set pwd = ? where name =?";//改操作
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);//给占位符复制,1表示第1个问号...
        preparedStatement.setString(2,pwd);
        int i = preparedStatement.executeUpdate();
        System.out.println((i>0?"操作成功":"操作失败"));
        //关闭资源
        preparedStatement.close();
        connection.close();
    }
}
